package com.example.academic_affairs_system.common;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.ArrayList;
import java.util.List;

/**
 * 统一响应信息体
 *
 * @author hjx
 * @since 2023/02/01 12:47 PM
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel("返回结果")
public class R {
  @ApiModelProperty("返回结果状态码")
  int code;

  @ApiModelProperty("返回结果信息")
  String msg;

  @JsonInclude(JsonInclude.Include.NON_NULL)
  @ApiModelProperty("原因")
  String desc;

  @JsonInclude(JsonInclude.Include.NON_NULL)
  @ApiModelProperty("返回结果数据")
  Object data;

  public static R customer(int code, String msg, String desc, Object data) {
    return R.builder().code(code).msg(msg).desc(desc).data(data).build();
  }

  public static R ok(Object data) {
    return customer(0, "请求成功", null, data);
  }

  public static R ok(String msg, Object data) {
    return customer(0, msg, null, data);
  }

  public static R fail() {
    return customer(-1, "请求失败", "调用数据接口，返回失败的状态", null);
  }

  public static R validate(BindingResult result) {
    List<FieldError> fieldErrors = result.getFieldErrors();
    List<String> msg = new ArrayList<>();
    for (FieldError fieldError : fieldErrors) {
      msg.add(fieldError.getDefaultMessage());
    }
    return R.builder().code(-999).msg(StrUtil.join(",", msg)).build();
  }
}
